package com.atguigu.spzx.manager.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.atguigu.spzx.exception.BaseException;
import com.atguigu.spzx.manager.mapper.ProductSpecMapper;
import com.atguigu.spzx.manager.service.IProductSpecService;
import com.atguigu.spzx.model.vo.common.entity.product.ProductSpec;
import com.atguigu.spzx.model.vo.common.page.PageInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 商品规格 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-03-10
 */
@Service
@RequiredArgsConstructor
public class ProductSpecServiceImpl extends ServiceImpl<ProductSpecMapper, ProductSpec> implements IProductSpecService {

    private final ProductSpecMapper productSpecMapper;

    /**
     * 分页查询商品规格
     * @param page
     * @param limit
     * @return
     */
    public PageInfo<ProductSpec> selectByPage(Integer page, Integer limit) {
        //查询条件是没有被逻辑删除
        LambdaQueryWrapper<ProductSpec> wrapper = new LambdaQueryWrapper<ProductSpec>().eq(ProductSpec::getIsDeleted, 0);
        //设置分页参数以及条件
        Page<ProductSpec> page1 = page(new Page<>(page, limit),wrapper);
        //创建响应实体
        PageInfo<ProductSpec> productSpecPageInfo = new PageInfo<>();
        //copy数据到响应实体
        BeanUtil.copyProperties(page1,productSpecPageInfo);
        //返回结果
        return productSpecPageInfo;
    }

    /**
     * 添加商品规格
     * @param productSpec
     */
    @Transactional
    public void add(ProductSpec productSpec) {
        //添加id值为空
        productSpec.setId(null);
        //时间
        productSpec.setCreateTime(LocalDateTime.now());
        productSpec.setUpdateTime(LocalDateTime.now());
        productSpec.setIsDeleted(0);
        boolean isSuccess = save(productSpec);
        if(!isSuccess) throw new BaseException("添加失败");
    }

    /**
     * 修改商品规格信息
     * @param productSpec
     */
    @Transactional
    public void update(ProductSpec productSpec) {
        //修改id不能为空
        if(productSpec.getId()==null) throw new BaseException("规格id不能为空");
        productSpecMapper.updateProSpec(productSpec);
    }

    /**
     * 根据id删除规格信息
     * @param id
     */
    public void deleteById(Long id) {
        productSpecMapper.deleteProSpec(id);
    }

    /**
     * 查询所有商品规格信息
     * @return
     */
    public List<ProductSpec> findAll() {
        return list();
    }
}
